package cn.coisini.model.common.log.service.impl;

import cn.coisini.mapper.AsyncOperLogMapper;
import cn.coisini.model.common.dtos.Result;
import cn.coisini.model.common.enums.ResultEnum;
import cn.coisini.model.common.exception.CustomAuthenticationException;
import cn.coisini.model.common.log.service.AsyncOperLogService;
import cn.coisini.model.pojo.AsyncOperLog;
import cn.coisini.model.vo.AsyncOperLogQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Optional;

import static cn.coisini.model.common.constants.AdminConstants.FALSE;

/**
 * @author xiangshaw
 * Description: 操作日志
 */
@Service
public class AsyncOperLogServiceImpl extends ServiceImpl<AsyncOperLogMapper, AsyncOperLog> implements AsyncOperLogService {

    /**
     * 保存操作日志
     */
    @Override
    public void saveSysLog(AsyncOperLog asyncOperLog) {
        baseMapper.insert(asyncOperLog);
        Result.ok(ResultEnum.SUCCESS);
    }

    // 条件分页查询操作日志
    @Override
    public Result<Page<AsyncOperLog>> pagingQuery(AsyncOperLogQueryVo asyncOperLogQueryVo) {
        QueryWrapper<AsyncOperLog> wrapper = getOperLogQueryWrapper(asyncOperLogQueryVo);
        // 分页条件（当前页、每页条数）
        Page<AsyncOperLog> page = new Page<>(asyncOperLogQueryVo.getCurrent(), asyncOperLogQueryVo.getLimit());
        Page<AsyncOperLog> operLogPage = page(page, wrapper);
        return Result.ok(operLogPage);
    }

    private static QueryWrapper<AsyncOperLog> getOperLogQueryWrapper(AsyncOperLogQueryVo asyncOperLogQueryVo) {
        // 获取条件值
        String title = asyncOperLogQueryVo.getTitle();
        String operName = asyncOperLogQueryVo.getOperName();
        String createTimeBegin = asyncOperLogQueryVo.getCreateTimeBegin();
        String createTimeEnd = asyncOperLogQueryVo.getCreateTimeEnd();
        // 封装条件
        QueryWrapper<AsyncOperLog> wrapper = new QueryWrapper<>();
        // 根据 标题、操作人、大于等于开始时间、小于等于创建时间
        if (!ObjectUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        if (!ObjectUtils.isEmpty(operName)) {
            wrapper.like("oper_name", operName);
        }
        // 大于等于开始时间
        if (!ObjectUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        } // 小于等于结束时间
        if (!ObjectUtils.isEmpty(createTimeBegin)) {
            wrapper.le("create_time", createTimeEnd);
        }// 排序
        wrapper.eq("del_flag", FALSE).orderByDesc("id");
        return wrapper;
    }

    // 根据id查询操作日志
    @Override
    public Result<AsyncOperLog> get(String id) {
        return Optional.ofNullable(id)
                .map(this::getById)
                .map(Result::ok)
                .orElse(Result.error(ResultEnum.DATA_NOT_EXIST));
    }

    // 根据id删除操作日志
    @Transactional
    @Override
    public Result<ResultEnum> removeOperLogById(String id) {
        return Optional.ofNullable(id)
                .map(this::getById)
                .map(operLog -> {
                    boolean removed = removeById(operLog.getId());
                    if (!removed) {
                        throw new CustomAuthenticationException(ResultEnum.LOG_DELETE_FAIL, ResultEnum.LOG_DELETE_FAIL.getMessage());
                    }
                    return Result.ok(ResultEnum.LOG_DELETE_SUCCESS);
                })
                .orElse(Result.error(ResultEnum.DATA_NOT_EXIST));
    }

    // 批量删除操作日志
    @Override
    @Transactional
    public Result<ResultEnum> batchRemove(List<String> ids) {
        return Optional.ofNullable(ids)
                .map(idList -> {
                    if (idList.isEmpty()) {
                        throw new IllegalArgumentException("ID 列表不能为空");
                    }
                    List<AsyncOperLog> operLogs = listByIds(idList);
                    if (operLogs.isEmpty()) {
                        throw new IllegalArgumentException("指定的操作日志不存在");
                    }
                    int i = baseMapper.deleteBatchIds(idList);
                    if (i != 0) {
                        return Result.ok(ResultEnum.SUCCESS);
                    }
                    throw new CustomAuthenticationException(ResultEnum.LOG_DELETE_FAIL, ResultEnum.LOG_DELETE_FAIL.getMessage());
                })
                .orElse(Result.error(ResultEnum.PARAM_ERROR.getCode(), "ID 列表不能为空"));

    }
}
